package com.fullhome8.cn.wanghongweb.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * JSON 操作工具类
 */
public class JsonUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final String CLIENT_REQUEST_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";



    public static GsonBuilder createGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
            @Override
            public Date deserialize(final JsonElement json, final Type typeOfT,
                                    final JsonDeserializationContext context) throws JsonParseException {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(CLIENT_REQUEST_DATETIME_PATTERN);
                    return sdf.parse(json.getAsString());
                } catch (ParseException e) {
                    throw new RuntimeException(
                            "日期{" + json.getAsString() + "}格式不对,Pattern应该为:" + CLIENT_REQUEST_DATETIME_PATTERN, e);
                } catch (Exception e) {
                    throw new RuntimeException("日期转换错误{" + json.toString() + "}", e);
                }
            }
        });
        gsonBuilder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
            @Override
            public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) {
                SimpleDateFormat sdf = new SimpleDateFormat(CLIENT_REQUEST_DATETIME_PATTERN);
                return new JsonPrimitive(sdf.format(arg0));
            }
        });
        return gsonBuilder;
    }

    /**
     * 将 Java 对象转为 JSON 字符串
     */
    public static <T> String toJSON(T obj) {
        String jsonStr;
        try {
            jsonStr = objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("Java 转 JSON 出错！", e);
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    /**
     * 将 JSON 字符串转为 Java 对象
     */
    public static <T> T fromJSON(String json, Class<T> type) {
        T obj;
        try {
            obj = objectMapper.readValue(json, type);
        } catch (Exception e) {
            logger.error("JSON 转 Java 出错！", e);
            throw new RuntimeException(e);
        }
        return obj;
    }

}
